import pandas as pd
import plotly.express as px
from nicegui import ui
import sys
import multiprocessing
import numpy as np
from datetime import datetime
import json
import os

# 用户数据存储路径
USER_DATA_FILE = "users.json"
# 登录状态管理
LOGGED_IN = False
CURRENT_USER = None


# 加载用户数据
def load_user_data():
    if os.path.exists(USER_DATA_FILE):
        try:
            with open(USER_DATA_FILE, 'r') as f:
                return json.load(f)
        except Exception as e:
            print(f"加载用户数据失败: {e}")
    return {}


# 保存用户数据
def save_user_data(users):
    try:
        with open(USER_DATA_FILE, 'w') as f:
            json.dump(users, f)
        return True
    except Exception as e:
        print(f"保存用户数据失败: {e}")
        return False


# 获取用户数据
users = load_user_data()


# 1. 数据加载与基本处理
def load_and_process_data(file_path):
    """加载数据集并进行基础处理"""
    try:
        df = pd.read_csv(file_path)
        print("数据加载成功，开始处理...")
        print(f"数据集列名: {df.columns.tolist()}")

        # 处理日期格式
        date_columns = ['Period Ending', 'Date', 'Fiscal Date Ending']
        found_date_col = None
        for col in date_columns:
            if col in df.columns:
                found_date_col = col
                df[col] = pd.to_datetime(df[col])
                df['Year'] = df[col].dt.year
                print(f"已使用 '{col}' 列创建年份信息")
                break

        if not found_date_col:
            print("警告: 未找到日期列，尝试从其他列推断年份")
            if 'Year' in df.columns:
                print("使用现有的 'Year' 列")
            else:
                # 如果没有日期列，创建模拟年份
                df['Year'] = np.random.randint(2015, 2023, size=len(df))
                print("创建模拟年份列")

        # 处理缺失值 - 使用均值填充数值列
        numeric_cols = df.select_dtypes(include=['float64', 'int64']).columns
        for col in numeric_cols:
            mean_val = df[col].mean()
            df[col] = df[col].fillna(mean_val)
            print(f"已填充列 {col} 的缺失值")

        print("数据处理完成")
        return df
    except Exception as e:
        print(f"数据加载或处理失败: {e}")
        return None


# 2. 数据探索与分析
def perform_analysis(df):
    """执行财务数据的分析"""
    if df is None:
        return {}

    analysis_results = {}

    # 2.1 按年份分析净利润
    if 'Net Income' in df.columns and 'Year' in df.columns:
        net_income_by_year = df.groupby('Year')['Net Income'].mean()
        analysis_results['net_income_by_year'] = net_income_by_year

        # 计算净利润增长率
        if len(net_income_by_year) > 1:
            growth_rates = net_income_by_year.pct_change()
            analysis_results['growth_rates'] = growth_rates

    # 2.2 分析主要财务指标的相关性
    key_metrics = ['Net Income', 'Gross Profit', 'Total Revenue', 'Operating Income',
                   'Total Assets', 'Total Liabilities', 'Earnings Per Share']
    available_metrics = [col for col in key_metrics if col in df.columns]
    print(f"可用的财务指标: {available_metrics}")

    if len(available_metrics) > 1:
        correlation = df[available_metrics].corr()
        analysis_results['correlation'] = correlation

    # 2.3 分析盈利能力指标
    profit_metrics = ['Profit Margin', 'Gross Margin', 'Operating Margin', 'Return on Assets']
    available_profit = [col for col in profit_metrics if col in df.columns]
    print(f"可用的利润率指标: {available_profit}")

    if available_profit:
        profit_by_year = df.groupby('Year')[available_profit].mean()
        analysis_results['profit_by_year'] = profit_by_year

    # 2.4 添加更多分析维度
    if 'Total Revenue' in df.columns and 'Total Assets' in df.columns:
        df['Asset Turnover'] = df['Total Revenue'] / df['Total Assets']
        analysis_results['asset_turnover'] = df.groupby('Year')['Asset Turnover'].mean()

    if 'Net Income' in df.columns and 'Total Assets' in df.columns:
        df['ROA'] = df['Net Income'] / df['Total Assets']
        analysis_results['roa'] = df.groupby('Year')['ROA'].mean()

    return analysis_results


# 3. 数据可视化
def create_visualizations(df, analysis_results):
    """创建多种可视化图表"""
    visualizations = {}
    print("开始创建可视化图表...")

    # 3.1 净利润趋势折线图
    if 'net_income_by_year' in analysis_results:
        net_income = analysis_results['net_income_by_year']
        plot_df = pd.DataFrame({
            'Year': net_income.index,
            'Net Income': net_income.values
        })

        fig = px.line(
            plot_df,
            x='Year',
            y='Net Income',
            title='年度净利润趋势',
            labels={'Year': '年份', 'Net Income': '净利润(美元)'}
        )
        fig.update_layout(
            yaxis=dict(tickformat=',.2f'),
            hovermode='x unified',
            template='plotly_white'
        )
        fig.update_traces(hovertemplate='%{y:,.2f}美元', line=dict(width=3))
        visualizations['net_income_trend'] = fig

    # 3.2 盈利能力指标对比图
    if 'profit_by_year' in analysis_results:
        profit_data = analysis_results['profit_by_year'].reset_index()
        profit_long = profit_data.melt(id_vars='Year', var_name='Metric', value_name='Value')

        fig = px.line(
            profit_long,
            x='Year',
            y='Value',
            color='Metric',
            title='年度盈利能力指标对比',
            labels={'Value': '百分比(%)', 'Metric': '指标类型'}
        )
        fig.update_layout(
            yaxis=dict(tickformat='.2%'),
            hovermode='x unified',
            template='plotly_white'
        )
        fig.update_traces(hovertemplate='%{y:.2%}', line=dict(width=3))
        visualizations['profitability_trend'] = fig

    # 3.3 财务指标相关性热力图
    if 'correlation' in analysis_results:
        corr = analysis_results['correlation']
        fig = px.imshow(
            corr,
            text_auto=True,
            title='财务指标相关性热力图',
            labels={'x': '指标', 'y': '指标', 'color': '相关系数'},
            color_continuous_scale='RdBu',
            zmin=-1, zmax=1
        )
        fig.update_layout(
            width=700,
            height=600,
            template='plotly_white'
        )
        visualizations['correlation_heatmap'] = fig

    # 3.4 公司净利润分布箱线图
    if 'Net Income' in df.columns and 'Year' in df.columns:
        # 添加公司标识，如果没有
        if 'Ticker Symbol' not in df.columns:
            if 'Company' in df.columns:
                df['Ticker Symbol'] = df['Company'].str[:3].str.upper()
            else:
                df['Ticker Symbol'] = 'COM'  # 默认值

        fig = px.box(
            df,
            x='Year',
            y='Net Income',
            color='Ticker Symbol',
            title='各公司年度净利润分布',
            labels={'Net Income': '净利润(美元)'},
            notched=True
        )
        fig.update_layout(
            yaxis=dict(tickformat=',.2f'),
            hovermode='y unified',
            template='plotly_white'
        )
        fig.update_traces(hovertemplate='%{y:,.2f}美元')
        visualizations['net_income_boxplot'] = fig

    # 3.5 添加柱状图 - 年度总收入比较
    if 'Total Revenue' in df.columns and 'Year' in df.columns:
        revenue_by_year = df.groupby('Year')['Total Revenue'].sum().reset_index()

        fig = px.bar(
            revenue_by_year,
            x='Year',
            y='Total Revenue',
            title='年度总收入比较',
            labels={'Total Revenue': '总收入(美元)', 'Year': '年份'},
            color='Total Revenue',
            color_continuous_scale='Blues'
        )
        fig.update_layout(
            yaxis=dict(tickformat=',.2f'),
            template='plotly_white'
        )
        fig.update_traces(hovertemplate='%{y:,.2f}美元')
        visualizations['revenue_bar'] = fig

    # 3.6 添加散点图 - 收入与利润关系
    if 'Total Revenue' in df.columns and 'Net Income' in df.columns:
        fig = px.scatter(
            df,
            x='Total Revenue',
            y='Net Income',
            title='总收入与净利润关系',
            labels={'Total Revenue': '总收入(美元)', 'Net Income': '净利润(美元)'},
            trendline='ols',
            trendline_color_override='red',
            hover_data=['Year'] if 'Year' in df.columns else None
        )
        fig.update_layout(
            xaxis=dict(tickformat=',.2f'),
            yaxis=dict(tickformat=',.2f'),
            template='plotly_white'
        )
        fig.update_traces(marker=dict(size=10, opacity=0.7))
        visualizations['revenue_income_scatter'] = fig

    # 3.7 添加3D散点图 - 财务指标分布
    if all(col in df.columns for col in ['Total Revenue', 'Net Income', 'Total Assets']):
        fig = px.scatter_3d(
            df,
            x='Total Revenue',
            y='Net Income',
            z='Total Assets',
            color='Ticker Symbol' if 'Ticker Symbol' in df.columns else 'Year',
            title='财务指标3D分布',
            labels={
                'Total Revenue': '总收入(美元)',
                'Net Income': '净利润(美元)',
                'Total Assets': '总资产(美元)'
            },
            hover_data=['Year'] if 'Year' in df.columns else None,
            size_max=20,
            opacity=0.7
        )
        fig.update_layout(
            scene=dict(
                xaxis=dict(title='总收入', tickprefix='$', tickformat=',.0f'),
                yaxis=dict(title='净利润', tickprefix='$', tickformat=',.0f'),
                zaxis=dict(title='总资产', tickprefix='$', tickformat=',.0f')
            ),
            margin=dict(l=0, r=0, b=0, t=30),
            template='plotly_white'
        )
        visualizations['financial_3d_scatter'] = fig

    print(f"已创建 {len(visualizations)} 个可视化图表")
    return visualizations


# 4. Web界面设计
def create_web_interface(df, visualizations, analysis_results):
    """使用NiceGUI创建交互式Web界面"""
    global main_content

    # 创建主内容区域，不嵌套在Column中
    with ui.header(elevated=True).style('background-color: #165DFF').classes('items-center justify-between'):
        # 标题居左
        ui.label('财务数据分析平台').classes('text-white text-2xl')

        # 登出按钮居右
        ui.button('登出', on_click=logout).classes('bg-red-500 hover:bg-red-700 text-white')

    # 使用flex布局使选项卡居中
    with ui.row().classes('w-full justify-center'):
        with ui.tabs().classes('flex justify-center') as tabs:
            tabs_list = ['概览', '盈利能力', '相关性分析', '分布分析', '高级分析']
            for tab_name in tabs_list:
                ui.tab(tab_name)

    with ui.tab_panels(tabs, value='概览') as main_content:
        # 概览页面
        with ui.tab_panel('概览'):
            ui.html('<h2 class="text-xl font-bold mb-4 text-center">财务数据概览</h2>')

            # 关键指标卡片 - 居中显示
            with ui.row().classes('w-full justify-center'):
                if 'net_income_by_year' in analysis_results:
                    net_income = analysis_results['net_income_by_year']
                    latest_year = net_income.index.max()
                    latest_income = net_income[latest_year]

                    with ui.card().classes('w-1/4 p-4 bg-blue-50'):
                        ui.label('最新年度净利润').classes('text-gray-600')
                        ui.label(f'${latest_income:,.2f}').classes('text-2xl font-bold text-blue-600')

                if 'Total Revenue' in df.columns:
                    total_revenue = df['Total Revenue'].sum()
                    with ui.card().classes('w-1/4 p-4 bg-green-50'):
                        ui.label('总收入').classes('text-gray-600')
                        ui.label(f'${total_revenue:,.2f}').classes('text-2xl font-bold text-green-600')

                if 'Total Assets' in df.columns:
                    total_assets = df['Total Assets'].sum()
                    with ui.card().classes('w-1/4 p-4 bg-purple-50'):
                        ui.label('总资产').classes('text-gray-600')
                        ui.label(f'${total_assets:,.2f}').classes('text-2xl font-bold text-purple-600')

                if 'Net Income' in df.columns and 'Total Revenue' in df.columns:
                    avg_margin = (df['Net Income'] / df['Total Revenue']).mean() * 100
                    with ui.card().classes('w-1/4 p-4 bg-yellow-50'):
                        ui.label('平均利润率').classes('text-gray-600')
                        ui.label(f'{avg_margin:.2f}%').classes('text-2xl font-bold text-yellow-600')

            # 图表网格 - 居中显示
            with ui.row().classes('w-full justify-center'):
                with ui.grid(columns=2).classes('w-5/6 mt-4 gap-4'):
                    if 'net_income_trend' in visualizations:
                        ui.plotly(visualizations['net_income_trend'])
                    if 'revenue_bar' in visualizations:
                        ui.plotly(visualizations['revenue_bar'])
                    if 'revenue_income_scatter' in visualizations:
                        ui.plotly(visualizations['revenue_income_scatter'])
                    if 'correlation_heatmap' in visualizations:
                        ui.plotly(visualizations['correlation_heatmap'])

            # 增长率表格 - 居中显示
            if 'growth_rates' in analysis_results:
                growth = analysis_results['growth_rates']
                ui.html('<h3 class="text-lg font-semibold mt-6 text-center">净利润增长率</h3>')

                # 创建格式化后的增长率数据
                growth_data = [
                    {'year': str(year), 'growth': f'{growth[year]:.2%}'}
                    for year in growth.index if not pd.isna(growth[year])
                ]

                with ui.row().classes('w-full justify-center'):
                    with ui.table(columns=[
                        {'name': 'year', 'label': '年份', 'field': 'year'},
                        {'name': 'growth', 'label': '增长率', 'field': 'growth'}
                    ], rows=growth_data).classes('w-1/2'):
                        pass

        # 盈利能力页面
        with ui.tab_panel('盈利能力'):
            ui.html('<h2 class="text-xl font-bold mb-4 text-center">盈利能力分析</h2>')

            # 盈利能力图表 - 居中对称显示
            with ui.row().classes('w-full justify-center'):
                if 'profitability_trend' in visualizations:
                    with ui.card().classes('w-4/5'):
                        ui.plotly(visualizations['profitability_trend'])

            # 盈利能力表格 - 居中对称显示
            if 'profit_by_year' in analysis_results:
                profit_data = analysis_results['profit_by_year']
                ui.html('<h3 class="text-lg font-semibold mt-6 text-center">各年度盈利能力指标</h3>')

                # 创建格式化后的数据
                columns = [{'name': 'year', 'label': '年份', 'field': 'year'}]
                for col in profit_data.columns:
                    columns.append({'name': col, 'label': f'{col}(%)', 'field': col})

                rows = []
                for year in profit_data.index:
                    row = {'year': str(year)}
                    for col in profit_data.columns:
                        row[col] = f'{profit_data.loc[year, col]:.2%}'
                    rows.append(row)

                with ui.row().classes('w-full justify-center'):
                    with ui.table(columns=columns, rows=rows).classes('w-4/5'):
                        pass

        # 相关性分析页面
        with ui.tab_panel('相关性分析'):
            ui.html('<h2 class="text-xl font-bold mb-4 text-center">财务指标相关性分析</h2>')

            # 相关性热力图 - 居中对称显示
            with ui.row().classes('w-full justify-center'):
                if 'correlation_heatmap' in visualizations:
                    with ui.card().classes('w-4/5'):
                        ui.plotly(visualizations['correlation_heatmap'])

            # 最强相关性展示 - 居中对称显示
            if 'correlation' in analysis_results:
                corr = analysis_results['correlation']
                corr_matrix = corr.stack().reset_index()
                corr_matrix.columns = ['Variable1', 'Variable2', 'Correlation']
                corr_matrix = corr_matrix[corr_matrix['Variable1'] != corr_matrix['Variable2']]

                # 获取最强正相关
                strongest_positive = corr_matrix.loc[corr_matrix['Correlation'].idxmax()]
                # 获取最强负相关
                strongest_negative = corr_matrix.loc[corr_matrix['Correlation'].idxmin()]

                with ui.row().classes('w-full justify-center'):
                    with ui.card().classes('w-4/5 mt-6 p-4 bg-blue-50'):
                        ui.label('最强相关性分析').classes('text-lg font-semibold mb-2 text-center')
                        with ui.row().classes('w-full justify-center'):
                            with ui.card().classes('w-1/2 p-4 bg-green-50'):
                                ui.label('最强正相关').classes('text-md font-semibold text-center')
                                ui.label(
                                    f"{strongest_positive['Variable1']} 和 {strongest_positive['Variable2']}").classes(
                                    'text-center')
                                ui.label(f"相关系数: {strongest_positive['Correlation']:.2f}").classes('text-center')
                            with ui.card().classes('w-1/2 p-4 bg-red-50'):
                                ui.label('最强负相关').classes('text-md font-semibold text-center')
                                ui.label(
                                    f"{strongest_negative['Variable1']} 和 {strongest_negative['Variable2']}").classes(
                                    'text-center')
                                ui.label(f"相关系数: {strongest_negative['Correlation']:.2f}").classes('text-center')

        # 分布分析页面
        with ui.tab_panel('分布分析'):
            ui.html('<h2 class="text-xl font-bold mb-4 text-center">财务指标3D分布分析</h2>')
            ui.html('<p class="text-gray-600 mb-4 text-center">交互式3D散点图展示总收入、净利润和总资产之间的关系</p>')

            # 3D散点图 - 居中对称显示
            with ui.row().classes('w-full justify-center'):
                if 'financial_3d_scatter' in visualizations:
                    with ui.card().classes('w-4/5'):
                        ui.plotly(visualizations['financial_3d_scatter'])

            # 添加简短的图表说明 - 居中对称显示
            with ui.row().classes('w-full justify-center'):
                with ui.card().classes('w-4/5 mt-4 p-4 bg-blue-50'):
                    ui.label('图表说明').classes('text-md font-semibold text-center')
                    ui.html('''
                        <div class="text-center">
                            <ul class="list-disc pl-6 inline-block text-left">
                                <li>此3D散点图展示了三个关键财务指标之间的关系</li>
                                <li>使用鼠标可以旋转、缩放和平移视图</li>
                                <li>悬停在点上查看详细信息</li>
                            </ul>
                        </div>
                    ''')

        # 高级分析页面
        with ui.tab_panel('高级分析'):
            ui.html('<h2 class="text-xl font-bold mb-4 text-center">高级财务分析</h2>')

            # 添加时间序列分解 - 居中对称显示
            if 'Net Income' in df.columns and 'Year' in df.columns:
                # 简单的时间序列分析
                fig = px.scatter(
                    df,
                    x='Year',
                    y='Net Income',
                    trendline="lowess",
                    title='净利润时间序列与趋势线',
                    labels={'Net Income': '净利润(美元)', 'Year': '年份'}
                )
                fig.update_layout(
                    yaxis=dict(tickformat=',.2f'),
                    template='plotly_white'
                )
                with ui.row().classes('w-full justify-center'):
                    with ui.card().classes('w-4/5'):
                        ui.plotly(fig)

            # 添加财务比率分析 - 居中对称显示
            if 'Total Revenue' in df.columns and 'Total Assets' in df.columns and 'Year' in df.columns:
                df['Asset Turnover'] = df['Total Revenue'] / df['Total Assets']
                turnover_by_year = df.groupby('Year')['Asset Turnover'].mean()

                fig = px.bar(
                    turnover_by_year.reset_index(),
                    x='Year',
                    y='Asset Turnover',
                    title='年度资产周转率',
                    labels={'Asset Turnover': '资产周转率', 'Year': '年份'}
                )
                fig.update_layout(
                    yaxis=dict(tickformat='.2f'),
                    template='plotly_white'
                )
                with ui.row().classes('w-full justify-center'):
                    with ui.card().classes('w-4/5 mt-4'):
                        ui.plotly(fig)

            # 添加财务健康度分析 - 居中对称显示
            if 'Total Assets' in df.columns and 'Total Liabilities' in df.columns and 'Year' in df.columns:
                df['Debt Ratio'] = df['Total Liabilities'] / df['Total Assets']
                debt_ratio_by_year = df.groupby('Year')['Debt Ratio'].mean()

                fig = px.line(
                    debt_ratio_by_year.reset_index(),
                    x='Year',
                    y='Debt Ratio',
                    title='年度负债比率趋势',
                    labels={'Debt Ratio': '负债比率', 'Year': '年份'}
                )
                fig.update_layout(
                    yaxis=dict(tickformat='.2%'),
                    template='plotly_white'
                )
                with ui.row().classes('w-full justify-center'):
                    with ui.card().classes('w-4/5 mt-4'):
                        ui.plotly(fig)


# 登录界面（全屏设计）
def show_login():
    global login_container, username_input, password_input

    # 隐藏主内容
    if 'main_content' in globals():
        main_content.visible = False

    # 清除现有登录界面
    if 'login_container' in globals():
        login_container.clear()

    # 创建全屏登录容器
    with ui.column().classes(
            'w-full h-full items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100') as login_container:
        # 登录卡片
        with ui.card().classes('w-full max-w-md p-8 shadow-xl rounded-xl bg-white'):
            ui.html('<div class="text-center mb-8">'
                    '<div class="text-3xl font-bold text-indigo-700 mb-2">财务数据分析平台</div>'
                    '<div class="text-gray-600">专业财务数据可视化与分析工具</div>'
                    '</div>')

            # 登录表单 - 显式设置value为空字符串
            with ui.column().classes('w-full gap-4'):
                username_input = ui.input('用户名', value='', placeholder='请输入您的用户名') \
                    .props('outlined autofocus') \
                    .classes('w-full')

                password_input = ui.input('密码', value='', password=True, placeholder='请输入您的密码') \
                    .props('outlined') \
                    .classes('w-full')

                login_button = ui.button('登录', on_click=login, icon='login') \
                    .props('unelevated') \
                    .classes('w-full bg-indigo-600 text-white hover:bg-indigo-700 h-10 mt-4')

                ui.separator().classes('w-full my-4')

                with ui.row().classes('w-full justify-between'):
                    ui.button('注册新账户', on_click=show_register, icon='person_add') \
                        .props('flat') \
                        .classes('text-indigo-600 hover:text-indigo-800')

                    ui.button('忘记密码?', on_click=lambda: ui.notify('请联系管理员重置密码'), icon='help') \
                        .props('flat') \
                        .classes('text-gray-600 hover:text-gray-800')

            # 页脚
            ui.html('<div class="text-center text-gray-500 text-xs mt-8 pt-4 border-t">'
                    '© 2023 财务数据分析平台 | 专业财务数据解决方案'
                    '</div>')

            # 添加回车键登录支持
            def handle_enter(event):
                if event.key == 'Enter':
                    login_button.click()

            username_input.on('keydown', handle_enter)
            password_input.on('keydown', handle_enter)


# 注册界面
def show_register():
    global register_dialog, reg_username_input, reg_password_input, reg_confirm_password

    # 如果已有注册对话框，先关闭
    if 'register_dialog' in globals() and register_dialog.value:
        register_dialog.close()

    # 创建注册对话框
    with ui.dialog() as register_dialog, ui.card().classes('w-full max-w-md p-6'):
        ui.html('<h2 class="text-xl font-bold mb-4 text-center text-indigo-700">创建新账户</h2>')

        # 使用Column代替Form，并显式设置value为空字符串
        with ui.column().classes('w-full gap-4'):
            reg_username_input = ui.input('用户名', value='', placeholder='设置您的用户名') \
                .props('outlined') \
                .classes('w-full')

            reg_password_input = ui.input('密码', value='', password=True, placeholder='设置您的密码') \
                .props('outlined') \
                .classes('w-full')

            reg_confirm_password = ui.input('确认密码', value='', password=True, placeholder='再次输入密码') \
                .props('outlined') \
                .classes('w-full')

            with ui.row().classes('w-full justify-center mt-2'):
                ui.button('注册', on_click=register, icon='how_to_reg') \
                    .props('unelevated') \
                    .classes('bg-indigo-600 hover:bg-indigo-700 text-white w-full h-10')

        # 底部链接
        with ui.row().classes('w-full justify-center mt-4'):
            ui.button('返回登录', on_click=lambda: register_dialog.close()) \
                .props('flat') \
                .classes('text-indigo-600 hover:text-indigo-800')

    register_dialog.open()


# 注册逻辑
def register():
    global users

    username = reg_username_input.value
    password = reg_password_input.value
    confirm_password = reg_confirm_password.value

    if not username or not password:
        ui.notify('用户名和密码不能为空', type='error')
        return

    if len(password) < 6:
        ui.notify('密码长度至少为6位', type='error')
        return

    if password != confirm_password:
        ui.notify('两次输入的密码不一致', type='error')
        return

    if username in users:
        ui.notify('用户名已存在', type='error')
        return

    # 添加新用户
    users[username] = password
    if save_user_data(users):
        # 注册成功后关闭对话框
        register_dialog.close()
        ui.notify('注册成功！请使用新账户登录', type='positive')

        # 自动填充用户名但不填充密码
        username_input.value = username
        password_input.value = ""

        # 将焦点设置在密码输入框
        password_input.run_method('focus')
    else:
        ui.notify('注册失败，请重试', type='error')


# 登录逻辑
def login():
    global LOGGED_IN, CURRENT_USER

    username = username_input.value
    password = password_input.value

    if not username or not password:
        ui.notify('请填写用户名和密码', type='error')
        return

    if username in users and users[username] == password:
        LOGGED_IN = True
        CURRENT_USER = username
        ui.notify(f'欢迎回来，{username}', type='positive')
        # 显示主界面
        main_content.visible = True
        # 隐藏登录界面
        login_container.visible = False
    else:
        ui.notify('用户名或密码错误', type='negative')


# 登出逻辑
def logout():
    global LOGGED_IN, CURRENT_USER
    LOGGED_IN = False
    CURRENT_USER = None
    ui.notify('您已安全登出', type='info')
    # 隐藏主界面
    main_content.visible = False
    # 显示登录界面
    show_login()


# 主函数
def main():
    global main_content, login_container

    file_path = 'fundamentals.csv'  # 替换为实际文件路径
    print(f"加载数据文件: {file_path}")

    # 1. 加载并处理数据
    df = load_and_process_data(file_path)
    if df is None:
        print("数据处理失败，程序终止")
        sys.exit(1)

    # 2. 执行数据分析
    analysis_results = perform_analysis(df)
    print(f"分析结果包含的键: {list(analysis_results.keys())}")

    # 3. 创建可视化图表
    visualizations = create_visualizations(df, analysis_results)
    print(f"可视化图表包含: {list(visualizations.keys())}")

    # 4. 检查是否有足够的可视化内容
    if not visualizations:
        print("没有足够的数据创建可视化图表")
        sys.exit(1)

    # 创建主界面，但初始不可见
    create_web_interface(df, visualizations, analysis_results)
    main_content.visible = False  # 初始隐藏主内容

    # 显示登录界面
    show_login()


# 修复Windows上的多进程问题
if __name__ in {"__main__", "__mp_main__"}:
    multiprocessing.freeze_support()
    main()
    ui.run(title='财务数据分析平台', port=8080, reload=False, dark=None)